// 全局变量
let currentUser = null;
let recognition = null;
let isRecording = false;
let newTravelPlans = new Set(); // 存储新创建的旅行计划ID
let newBudgetAnalyses = new Set(); // 存储新创建的费用预算分析ID

// API基础URL - 使用相对路径避免跨域问题
const API_BASE = '/api';

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
    initializeLocationInfo();
});

// 初始化应用
function initializeApp() {
    // 检查是否已登录
    const savedUser = localStorage.getItem('currentUser');
    if (savedUser) {
        currentUser = JSON.parse(savedUser);
        showMainInterface();
    } else {
        showLoginInterface();
    }

    // 绑定事件监听器
    bindEventListeners();
    
    // 初始化语音识别
    initializeSpeechRecognition();
}

// 绑定事件监听器
function bindEventListeners() {
    // 登录注册表单
    document.getElementById('login-form').addEventListener('submit', handleLogin);
    document.getElementById('register-form').addEventListener('submit', handleRegister);
    
    // 导航菜单
    document.querySelectorAll('.nav-item').forEach(item => {
        item.addEventListener('click', handleNavigation);
    });
    
    // 刷新按钮
    document.getElementById('refresh-travel-plans').addEventListener('click', loadTravelPlans);
    document.getElementById('refresh-budget-analysis').addEventListener('click', loadBudgetAnalysis);
    
    // 退出按钮
    document.getElementById('logout-btn').addEventListener('click', handleLogout);
    
    // 模态框关闭
    document.getElementById('close-modal').addEventListener('click', closeModal);
    document.getElementById('close-voice-modal').addEventListener('click', closeVoiceModal);
    

    
    // 语音模态框按钮
    document.getElementById('start-recording').addEventListener('click', startRecording);
    document.getElementById('stop-recording').addEventListener('click', stopRecording);
    document.getElementById('submit-voice').addEventListener('click', submitVoiceInput);
    
    // 语音功能按钮事件将在登录成功后绑定（在showMainInterface函数中）
    
    // 点击模态框背景关闭
    document.getElementById('modal').addEventListener('click', function(e) {
        if (e.target === this) closeModal();
    });
    
    document.getElementById('voice-modal').addEventListener('click', function(e) {
        if (e.target === this) closeVoiceModal();
    });
}

// 显示登录界面
function showLoginInterface() {
    document.getElementById('login-container').classList.remove('hidden');
    document.getElementById('main-container').classList.add('hidden');
}

// 显示主界面
function showMainInterface() {
    document.getElementById('login-container').classList.add('hidden');
    document.getElementById('main-container').classList.remove('hidden');
    
    // 更新用户信息
    document.getElementById('user-name').textContent = currentUser.userName || '用户';
    document.getElementById('user-id').textContent = `(${currentUser.userId})`;
    
    // 绑定语音按钮事件（确保按钮存在后再绑定）
    bindVoiceButtonEvents();
    
    // 加载初始数据
    loadTravelPlans();
}

// 绑定语音按钮事件
function bindVoiceButtonEvents() {
    // 智能行程规划按钮
    const voicePlanBtn = document.getElementById('voice-plan-btn');
    if (voicePlanBtn) {
        // 移除之前可能绑定的事件
        voicePlanBtn.replaceWith(voicePlanBtn.cloneNode(true));
        const newVoicePlanBtn = document.getElementById('voice-plan-btn');
        
        newVoicePlanBtn.addEventListener('mousedown', startVoicePlan);
        newVoicePlanBtn.addEventListener('mouseup', stopVoicePlan);
        newVoicePlanBtn.addEventListener('mouseleave', stopVoicePlan);
        newVoicePlanBtn.addEventListener('touchstart', startVoicePlan);
        newVoicePlanBtn.addEventListener('touchend', stopVoicePlan);
        newVoicePlanBtn.addEventListener('touchcancel', stopVoicePlan);
    }
    
    // 费用预算分析按钮
    const voiceBudgetBtn = document.getElementById('voice-budget-btn');
    if (voiceBudgetBtn) {
        // 移除之前可能绑定的事件
        voiceBudgetBtn.replaceWith(voiceBudgetBtn.cloneNode(true));
        const newVoiceBudgetBtn = document.getElementById('voice-budget-btn');
        
        newVoiceBudgetBtn.addEventListener('mousedown', startVoiceBudget);
        newVoiceBudgetBtn.addEventListener('mouseup', stopVoiceBudget);
        newVoiceBudgetBtn.addEventListener('mouseleave', stopVoiceBudget);
        newVoiceBudgetBtn.addEventListener('touchstart', startVoiceBudget);
        newVoiceBudgetBtn.addEventListener('touchend', stopVoiceBudget);
        newVoiceBudgetBtn.addEventListener('touchcancel', stopVoiceBudget);
    }
}

// 标签页切换
function showTab(tabName, event) {
    // 隐藏所有标签内容
    document.querySelectorAll('.tab-content').forEach(tab => {
        tab.classList.remove('active');
    });
    
    // 移除所有标签按钮的active类
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    
    // 显示选中的标签内容
    document.getElementById(tabName + '-tab').classList.add('active');
    
    // 激活选中的标签按钮
    if (event && event.target) {
        event.target.classList.add('active');
    }
}

// 处理登录
async function handleLogin(e) {
    e.preventDefault();
    
    const userId = document.getElementById('login-userId').value;
    const password = document.getElementById('login-password').value;
    
    try {
        const response = await fetch(`${API_BASE}/user/login`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            credentials: 'include', // 包含cookie以支持session
            body: JSON.stringify({
                userId: userId,
                password: password
            })
        });
        
        const result = await response.json();
        
        if (result.success) {
            currentUser = {
                userId: result.data.userId,
                userName: result.data.userName || '用户'
            };
            localStorage.setItem('currentUser', JSON.stringify(currentUser));
            showMainInterface();
        } else {
            alert('登录失败: ' + result.errorMsg);
        }
    } catch (error) {
        console.error('登录错误:', error);
        alert('登录失败，请检查网络连接');
    }
}

// 处理注册
async function handleRegister(e) {
    e.preventDefault();
    
    const userName = document.getElementById('register-userName').value;
    const userId = document.getElementById('register-userId').value;
    const password = document.getElementById('register-password').value;
    
    try {
        const response = await fetch(`${API_BASE}/user/registry`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                userName: userName,
                userId: userId,
                password: password
            })
        });
        
        const result = await response.json();
        
        if (result.success) {
            alert('注册成功，请登录');
            showTab('login', e);
            // 清空注册表单
            document.getElementById('register-form').reset();
        } else {
            alert('注册失败: ' + result.errorMsg);
        }
    } catch (error) {
        console.error('注册错误:', error);
        alert('注册失败，请检查网络连接');
    }
}

// 处理退出
async function handleLogout() {
    try {
        await fetch(`${API_BASE}/user/logout`, {
            method: 'POST',
            credentials: 'include' // 包含cookie以支持session
        });
    } catch (error) {
        console.error('退出错误:', error);
    }
    
    // 清除本地存储
    localStorage.removeItem('currentUser');
    currentUser = null;
    showLoginInterface();
}

// 处理导航
function handleNavigation(e) {
    e.preventDefault();
    
    const targetSection = this.getAttribute('data-section');
    
    // 移除所有导航项的active类
    document.querySelectorAll('.nav-item').forEach(item => {
        item.classList.remove('active');
    });
    
    // 隐藏所有内容区域
    document.querySelectorAll('.content-section').forEach(section => {
        section.classList.remove('active');
    });
    
    // 激活选中的导航项和内容区域
    this.classList.add('active');
    document.getElementById(targetSection).classList.add('active');
    
    // 加载对应数据
    if (targetSection === 'travel-plans') {
        loadTravelPlans();
    } else if (targetSection === 'budget-analysis') {
        loadBudgetAnalysis();
    } else if (targetSection === 'amap') {
        initAmap();
    } else if (targetSection === 'universal-assistant') {
        initUniversalAssistant();
    }
}

// 加载旅行计划列表
async function loadTravelPlans() {
    const listContainer = document.getElementById('travel-plans-list');
    listContainer.innerHTML = '<div class="loading"></div> 加载中...';
    
    try {
        const response = await fetch(`${API_BASE}/user/query_travel_plans?userId=${currentUser.userId}`, {
            credentials: 'include' // 包含cookie以支持session
        });
        const result = await response.json();
        
        if (result.success) {
            // data可能是数组或对象，统一处理为数组
            const data = Array.isArray(result.data) ? result.data : [result.data];
            displayTravelPlans(data || []);
        } else {
            listContainer.innerHTML = '<div class="empty-state"><div class="icon">📝</div><p>加载失败: ' + result.errorMsg + '</p></div>';
        }
    } catch (error) {
        console.error('加载旅行计划错误:', error);
        listContainer.innerHTML = '<div class="empty-state"><div class="icon">❌</div><p>加载失败，请检查网络连接</p></div>';
    }
}

// 显示旅行计划列表
function displayTravelPlans(plans) {
    const listContainer = document.getElementById('travel-plans-list');
    
    if (!plans || plans.length === 0) {
        listContainer.innerHTML = `
            <div class="empty-state">
                <div class="icon">📝</div>
                <h3>暂无行程规划</h3>
                <p>点击"智能行程规划"按钮创建您的第一个旅行计划</p>
            </div>
        `;
        return;
    }
    
    listContainer.innerHTML = plans.map(plan => {
        const isNew = newTravelPlans.has(plan.planId);
        return `
        <div class="list-item ${isNew ? 'new-item' : ''}">
            <div class="item-info">
                <div class="item-name" onclick="showTravelPlanDetail('${plan.planId}')">
                    ${plan.planName || '未命名计划'}
                    ${isNew ? '<span class="new-badge">新</span>' : ''}
                </div>
                <div class="item-time">创建时间: ${formatDate(plan.createTime)}</div>
            </div>
            <div class="item-actions">
                <button class="btn-secondary" onclick="deleteTravelPlan('${plan.planId}')">删除</button>
            </div>
        </div>
    `;
    }).join('');
}

// 显示旅行计划详情
async function showTravelPlanDetail(planId) {
    try {
        const response = await fetch(`${API_BASE}/user/get_travel_plan_detail?planId=${planId}`, {
            credentials: 'include' // 包含cookie以支持session
        });
        const result = await response.json();
        
        if (result.success) {
            // 移除新数据标签
            if (newTravelPlans.has(planId)) {
                newTravelPlans.delete(planId);
                // 重新加载列表以更新显示
                loadTravelPlans();
            }
            
            showModal('旅行计划详情', createTravelPlanDetailContent(result.data, planId));
        } else {
            alert('获取详情失败: ' + result.errorMsg);
        }
    } catch (error) {
        console.error('获取旅行计划详情错误:', error);
        alert('获取详情失败，请检查网络连接');
    }
}

// 创建旅行计划详情内容
function createTravelPlanDetailContent(planData, planId) {
    // 解析HTML内容中的换行符
    const formattedContent = (planData.planContent || '').replace(/<br\/?>/g, '\n').replace(/<br\s*\/?>/g, '\n');
    
    return `
        <div class="plan-detail-header">
            <h3>${planData.planName || '未命名计划'}</h3>
            <div class="plan-meta">
            
                <span>创建时间: ${formatDate(planData.createTime)}</span>
                <span>更新时间: ${formatDate(planData.updateTime) || '无'}</span>
            </div>
        </div>
        <div class="plan-content">
            <h4>旅行计划内容:</h4>
            <textarea id="plan-edit-area" class="edit-area" rows="15">${formattedContent}</textarea>
        </div>
        <div class="edit-actions">
            <button class="btn-secondary" onclick="closeModal()">取消</button>
            <button class="btn-primary" onclick="updateTravelPlan('${planId}')">保存更新</button>
        </div>
    `;
}

// 更新旅行计划
async function updateTravelPlan(planId) {
    const content = document.getElementById('plan-edit-area').value;
    
    try {
        const response = await fetch(`${API_BASE}/user/update_travel_plan`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            credentials: 'include', // 包含cookie以支持session
            body: JSON.stringify({
                planId: planId,
                planContent: content
            })
        });
        
        const result = await response.json();
        
        if (result.success) {
            alert('更新成功');
            closeModal();
            loadTravelPlans();
        } else {
            alert('更新失败: ' + result.errorMsg);
        }
    } catch (error) {
        console.error('更新旅行计划错误:', error);
        alert('更新失败，请检查网络连接');
    }
}

// 删除旅行计划
async function deleteTravelPlan(planId) {
    if (!confirm('确定要删除这个旅行计划吗？')) {
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE}/travel/delete_travel_plan?planId=${planId}`, {
            method: 'DELETE',
            credentials: 'include' // 包含cookie以支持session
        });
        
        const result = await response.json();
        
        if (result.success) {
            alert('删除成功');
            loadTravelPlans();
        } else {
            alert('删除失败: ' + result.errorMsg);
        }
    } catch (error) {
        console.error('删除旅行计划错误:', error);
        alert('删除失败，请检查网络连接');
    }
}

// 加载费用预算分析列表
async function loadBudgetAnalysis() {
    const listContainer = document.getElementById('budget-analysis-list');
    listContainer.innerHTML = '<div class="loading"></div> 加载中...';
    
    try {
        const response = await fetch(`${API_BASE}/budget/query_budget_analysis?userId=${currentUser.userId}`, {
            credentials: 'include' // 包含cookie以支持session
        });
        const result = await response.json();
        
        if (result.success) {
            // data可能是数组或对象，统一处理为数组
            const data = Array.isArray(result.data) ? result.data : [result.data];
            displayBudgetAnalysis(data || []);
        } else {
            const errorMsg = result.errorMsg || '未知错误';
            listContainer.innerHTML = '<div class="empty-state"><div class="icon">💰</div><p>加载失败: ' + errorMsg + '</p></div>';
        }
    } catch (error) {
        console.error('加载预算分析错误:', error);
        listContainer.innerHTML = '<div class="empty-state"><div class="icon">❌</div><p>加载失败，请检查网络连接</p></div>';
    }
}

// 显示费用预算分析列表
function displayBudgetAnalysis(analyses) {
    const listContainer = document.getElementById('budget-analysis-list');
    
    if (!analyses || analyses.length === 0) {
        listContainer.innerHTML = `
            <div class="empty-state">
                <div class="icon">💰</div>
                <h3>暂无费用预算分析</h3>
                <p>点击"预算分析"按钮创建您的第一个费用预算分析</p>
            </div>
        `;
        return;
    }
    
    listContainer.innerHTML = analyses.map(analysis => {
        const isNew = newBudgetAnalyses.has(analysis.analyzeId);
        return `
        <div class="list-item ${isNew ? 'new-item' : ''}">
            <div class="item-info">
                <div class="item-name" onclick="showBudgetAnalysisDetail('${analysis.analyzeId}')">
                    ${analysis.analyzeName || '未命名分析'}
                    ${isNew ? '<span class="new-badge">新</span>' : ''}
                </div>
                <div class="item-time">创建时间: ${formatDate(analysis.createTime)}</div>
            </div>
            <div class="item-actions">
                <button class="btn-secondary" onclick="deleteBudgetAnalysis('${analysis.analyzeId}')">删除</button>
            </div>
        </div>
    `;
    }).join('');
}

// 创建费用预算分析详情内容
function createBudgetAnalysisDetailContent(analysisData, analysisId) {
    // 解析HTML内容中的换行符
    const formattedContent = (analysisData.analyzeContent || '').replace(/<br\/?>/g, '\n').replace(/<br\s*\/?>/g, '\n');
    
    return `
        <div class="plan-detail-header">
            <h3>${analysisData.analyzeName || '未命名分析'}</h3>
            <div class="plan-meta">
             
                <span>创建时间: ${formatDate(analysisData.createTime)}</span>
            </div>
        </div>
        <div class="plan-content">
            <h4>费用预算分析内容:</h4>
            <textarea id="analysis-edit-area" class="edit-area" rows="15" readonly>${formattedContent}</textarea>
        </div>
        <div class="edit-actions">
            <button class="btn-secondary" onclick="closeModal()">关闭</button>
        </div>
    `;
}

// 显示费用预算分析详情
async function showBudgetAnalysisDetail(analysisId) {
    try {
        const response = await fetch(`${API_BASE}/budget/analysis_info?analysisId=${analysisId}`, {
            credentials: 'include' // 包含cookie以支持session
        });
        const result = await response.json();
        
        if (result.success) {
            // 移除新标记
            if (newBudgetAnalyses.has(analysisId)) {
                newBudgetAnalyses.delete(analysisId);
            }
            showModal('预算分析详情', createBudgetAnalysisDetailContent(result.data, analysisId));
        } else {
            alert('获取详情失败: ' + result.errorMsg);
        }
    } catch (error) {
        console.error('获取预算分析详情错误:', error);
        alert('获取详情失败，请检查网络连接');
    }
}

// 删除费用预算分析
async function deleteBudgetAnalysis(analysisId) {
    if (!confirm('确定要删除这个费用预算分析吗？')) {
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE}/budget/delete_budget_analysis?analysisId=${analysisId}`, {
            method: 'DELETE',
            credentials: 'include' // 包含cookie以支持session
        });
        
        const result = await response.json();
        
        if (result.success) {
            alert('删除成功');
            loadBudgetAnalysis();
        } else {
            alert('删除失败: ' + result.errorMsg);
        }
    } catch (error) {
        console.error('删除预算分析错误:', error);
        alert('删除失败，请检查网络连接');
    }
}

// 语音功能相关
function initializeSpeechRecognition() {
    if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) {
        const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
        recognition = new SpeechRecognition();
        recognition.continuous = false;
        recognition.interimResults = true;
        recognition.lang = 'zh-CN';
        
        recognition.onstart = function() {
            isRecording = true;
            updateVoiceStatus('录音中...');
            startVoiceWaveAnimation();
        };
        
        recognition.onresult = function(event) {
            let transcript = '';
            for (let i = event.resultIndex; i < event.results.length; i++) {
                if (event.results[i].isFinal) {
                    transcript += event.results[i][0].transcript;
                } else {
                    transcript += event.results[i][0].transcript;
                }
            }
            document.getElementById('voice-text').textContent = transcript;
        };
        
        recognition.onend = function() {
            isRecording = false;
            stopVoiceWaveAnimation();
            if (document.getElementById('voice-text').textContent) {
                updateVoiceStatus('录音完成');
                document.getElementById('stop-recording').classList.add('hidden');
                document.getElementById('submit-voice').classList.remove('hidden');
            } else {
                updateVoiceStatus('录音失败，请重试');
            }
        };
        
        recognition.onerror = function(event) {
            console.error('语音识别错误:', event.error);
            updateVoiceStatus('录音错误: ' + event.error);
            isRecording = false;
            stopVoiceWaveAnimation();
        };
    } else {
        console.warn('浏览器不支持语音识别');
    }
}

// 全局变量用于语音录制




// 显示语音输入模态框
function showVoiceModal(title) {
    document.getElementById('voice-modal-title').textContent = title + ' - 语音输入';
    document.getElementById('voice-modal').classList.remove('hidden');
    resetVoiceModal();
}

// 重置语音模态框
function resetVoiceModal() {
    updateVoiceStatus('准备录音...');
    document.getElementById('voice-text').textContent = '';
    document.getElementById('start-recording').classList.remove('hidden');
    document.getElementById('stop-recording').classList.add('hidden');
    document.getElementById('submit-voice').classList.add('hidden');
    stopVoiceWaveAnimation();
}

// 开始录音
function startRecording() {
    if (recognition && !isRecording) {
        recognition.start();
        document.getElementById('start-recording').classList.add('hidden');
        document.getElementById('stop-recording').classList.remove('hidden');
    }
}

// 停止录音
function stopRecording() {
    if (recognition && isRecording) {
        recognition.stop();
    }
}



// 标记最新创建的旅行计划为新数据
async function markNewTravelPlans() {
    try {
        const response = await fetch(`${API_BASE}/user/query_travel_plans?userId=${currentUser.userId}`, {
            credentials: 'include' // 包含cookie以支持session
        });
        const result = await response.json();
        
        if (result.success) {
            const data = Array.isArray(result.data) ? result.data : [result.data];
            if (data.length > 0) {
                // 获取最新的旅行计划（按创建时间倒序的第一个）
                const latestPlan = data[0];
                // 标记为新数据
                newTravelPlans.add(latestPlan.planId);
                // 重新显示列表以更新标签
                displayTravelPlans(data);
            }
        }
    } catch (error) {
        console.error('标记新旅行计划错误:', error);
    }
}

// 显示处理中消息
function showProcessingMessage() {
    // 显示友好的处理中提示
    const processingMessage = document.createElement('div');
    processingMessage.id = 'processing-message';
    processingMessage.innerHTML = `
        <div style="position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); 
                    background: rgba(0, 0, 0, 0.8); color: white; padding: 20px; 
                    border-radius: 10px; z-index: 1000; text-align: center;">
            <div style="font-size: 18px; margin-bottom: 10px;">🚀 正在处理您的语音输入</div>
            <div style="font-size: 14px; opacity: 0.8;">请稍候，我们正在为您生成旅行计划...</div>
            <div style="margin-top: 15px; font-size: 12px; opacity: 0.6;">
                完成后请刷新旅行计划列表查看新计划
            </div>
        </div>
    `;
    document.body.appendChild(processingMessage);
}

// 移除处理中消息
function removeProcessingMessage() {
    const processingMessage = document.getElementById('processing-message');
    if (processingMessage) {
        processingMessage.remove();
    }
}

// 显示成功消息
function showSuccessMessage(message) {
    removeProcessingMessage();
    
    const successMessage = document.createElement('div');
    successMessage.id = 'success-message';
    successMessage.innerHTML = `
        <div style="position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); 
                    background: rgba(76, 175, 80, 0.9); color: white; padding: 20px; 
                    border-radius: 10px; z-index: 1000; text-align: center;">
            <div style="font-size: 18px; margin-bottom: 10px;">✅ 处理成功</div>
            <div style="font-size: 14px;">${message}</div>
        </div>
    `;
    document.body.appendChild(successMessage);
    
    // 2秒后自动移除
    setTimeout(() => {
        removeSuccessMessage();
    }, 2000);
}

// 移除成功消息
function removeSuccessMessage() {
    const successMessage = document.getElementById('success-message');
    if (successMessage) {
        successMessage.remove();
    }
}

// 显示错误消息
function showErrorMessage(message) {
    removeProcessingMessage();
    
    const errorMessage = document.createElement('div');
    errorMessage.id = 'error-message';
    errorMessage.innerHTML = `
        <div style="position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); 
                    background: rgba(244, 67, 54, 0.9); color: white; padding: 20px; 
                    border-radius: 10px; z-index: 1000; text-align: center;">
            <div style="font-size: 18px; margin-bottom: 10px;">❌ 处理失败</div>
            <div style="font-size: 14px;">${message}</div>
        </div>
    `;
    document.body.appendChild(errorMessage);
    
    // 2秒后自动移除
    setTimeout(() => {
        removeErrorMessage();
    }, 2000);
}

// 移除错误消息
function removeErrorMessage() {
    const errorMessage = document.getElementById('error-message');
    if (errorMessage) {
        errorMessage.remove();
    }
}

// 提交语音输入（保留原有功能，用于文本输入）
async function submitVoiceInput() {
    const text = document.getElementById('voice-text').textContent;
    if (!text.trim()) {
        alert('请输入语音内容');
        return;
    }
    
    try {
        let apiUrl, requestBody;
        
        if (currentVoiceType === 'plan') {
            apiUrl = `${API_BASE}/api/v1/generate_travel_plan`;
            requestBody = {
                userId: currentUser.userId,
                userInput: text
            };
        } else {
            apiUrl = `${API_BASE}/api/v1/budget_analyze`;
            requestBody = {
                userId: currentUser.userId,
                userInput: text
            };
        }
        
        const response = await fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            credentials: 'include', // 包含cookie以支持session
            body: JSON.stringify(requestBody)
        });
        
        const result = await response.json();
        
        if (result.success) {
            alert((currentVoiceType === 'plan' ? '行程规划' : '预算分析') + '生成成功！');
            closeVoiceModal();
            
            // 刷新对应列表
            if (currentVoiceType === 'plan') {
                loadTravelPlans();
            } else {
                loadBudgetAnalysis();
            }
        } else {
            alert('生成失败: ' + result.errorMsg);
        }
    } catch (error) {
        console.error('提交语音输入错误:', error);
        alert('生成失败，请检查网络连接');
    }
}

// 更新语音状态
function updateVoiceStatus(status) {
    document.getElementById('voice-status').textContent = status;
}

// 开始声波动画
function startVoiceWaveAnimation() {
    const waveElement = document.getElementById('voice-wave');
    waveElement.innerHTML = '<div class="loading"></div>';
}

// 停止声波动画
function stopVoiceWaveAnimation() {
    const waveElement = document.getElementById('voice-wave');
    waveElement.innerHTML = '';
}

// 关闭语音模态框
function closeVoiceModal() {
    if (isRecording) {
        stopRecording();
    }
    document.getElementById('voice-modal').classList.add('hidden');
}

// 模态框相关
function showModal(title, content) {
    document.getElementById('modal-title').textContent = title;
    document.getElementById('modal-content').innerHTML = content;
    document.getElementById('modal').classList.remove('hidden');
}

function closeModal() {
    document.getElementById('modal').classList.add('hidden');
}

// 工具函数
function formatDate(dateString) {
    if (!dateString) return '未知时间';
    
    try {
        const date = new Date(dateString);
        return date.toLocaleString('zh-CN');
    } catch (error) {
        return dateString;
    }
}

// 键盘快捷键支持
document.addEventListener('keydown', function(e) {
    // ESC键关闭模态框
    if (e.key === 'Escape') {
        if (!document.getElementById('modal').classList.contains('hidden')) {
            closeModal();
        }
        if (!document.getElementById('voice-modal').classList.contains('hidden')) {
            closeVoiceModal();
        }
    }
});

// ==================== 语音功能按钮实现 ====================

// 全局变量用于语音录制
let currentVoiceType = '';
let mediaRecorder = null;
let audioChunks = [];
let isRecordingVoice = false;

// 开始智能行程规划语音录制
function startVoicePlan() {
    startVoiceRecording('plan');
}

// 停止智能行程规划语音录制
function stopVoicePlan() {
    stopVoiceRecording();
}

// 开始费用预算分析语音录制
function startVoiceBudget() {
    startVoiceRecording('budget');
}

// 停止费用预算分析语音录制
function stopVoiceBudget() {
    stopVoiceRecording();
}

// 开始语音录制
function startVoiceRecording(type) {
    if (isRecordingVoice) return;
    
    currentVoiceType = type;
    isRecordingVoice = true;
    
    // 更新按钮状态
    updateVoiceButtonState(type, true);
    
    // 请求麦克风权限并开始录制
    navigator.mediaDevices.getUserMedia({ audio: true })
        .then(stream => {
            audioChunks = [];
            mediaRecorder = new MediaRecorder(stream);
            
            mediaRecorder.ondataavailable = event => {
                audioChunks.push(event.data);
            };
            
            mediaRecorder.onstop = async () => {
                // 根据类型调用不同的接口
                if (type === 'plan') {
                    await processRecording(audioChunks);
                } else if (type === 'budget') {
                    await processBudgetRecording(audioChunks);
                }
                
                // 停止所有音频轨道
                stream.getTracks().forEach(track => track.stop());
            };
            
            mediaRecorder.start();
        })
        .catch(error => {
            console.error('获取麦克风权限失败:', error);
            showErrorMessage('无法访问麦克风，请检查权限设置');
            isRecordingVoice = false;
            updateVoiceButtonState(type, false);
        });
}

// 停止语音录制
function stopVoiceRecording() {
    if (!isRecordingVoice || !mediaRecorder) return;
    
    isRecordingVoice = false;
    
    // 更新按钮状态
    updateVoiceButtonState(currentVoiceType, false);
    
    // 停止录制
    if (mediaRecorder.state === 'recording') {
        mediaRecorder.stop();
    }
}

// 更新语音按钮状态
function updateVoiceButtonState(type, isRecording) {
    const button = document.getElementById(`voice-${type}-btn`);
    const indicator = button.querySelector('.voice-indicator');
    
    if (isRecording) {
        button.classList.add('recording');
        indicator.textContent = '录制中...';
    } else {
        button.classList.remove('recording');
        indicator.textContent = '按住说话';
    }
}

// 处理录制的音频
async function processRecording(audioChunks) {
    if (audioChunks.length === 0) {
        return;
    }

    try {
        const audioBlob = new Blob(audioChunks, { type: 'audio/webm' });
        
        // 显示处理中提示
        showProcessingMessage('正在制定旅行计划...');
        
        // 将音频转换为PCM格式
        const pcmData = await convertToPCM(audioBlob);
        
        // 转换为字节数组
        const byteArray = new Uint8Array(pcmData.buffer);
        
        // 发送POST请求到/asr/stream接口
        const response = await fetch(`${API_BASE}/asr/stream`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/octet-stream',
            },
            credentials: 'include',
            body: byteArray
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const result = await response.json();
        
        if (result.success) {
            showSuccessMessage('智能行程规划生成成功！');
            // 标记新创建的旅行计划
            await markNewTravelPlan();
            // 刷新旅行计划列表
            loadTravelPlans();
        } else {
            showErrorMessage('处理失败: ' + result.errorMsg);
        }
        
    } catch (error) {
        console.error('音频处理失败:', error);
        showErrorMessage('音频处理失败，请重试');
    }
}

// 处理费用预算分析录制的音频
async function processBudgetRecording(audioChunks) {
    if (audioChunks.length === 0) {
        return;
    }

    try {
        const audioBlob = new Blob(audioChunks, { type: 'audio/webm' });
        
        // 显示处理中提示
        showProcessingMessage('正在分析费用预算...');
        
        // 将音频转换为PCM格式
        const pcmData = await convertToPCM(audioBlob);
        
        // 转换为字节数组
        const byteArray = new Uint8Array(pcmData.buffer);
        
        // 发送POST请求到/asr/stream/budget_analyze接口
        const response = await fetch(`${API_BASE}/asr/stream/budget_analyze`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/octet-stream',
            },
            credentials: 'include',
            body: byteArray
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const result = await response.json();
        
        if (result.success) {
            showSuccessMessage('费用预算分析生成成功！');
            // 标记新创建的费用预算分析
            await markNewBudgetAnalysis();
            // 刷新费用预算分析列表
            loadBudgetAnalysis();
        } else {
            showErrorMessage('处理失败: ' + result.errorMsg);
        }
        
    } catch (error) {
        console.error('音频处理失败:', error);
        showErrorMessage('音频处理失败，请重试');
    }
}



// 标记新创建的旅行计划
async function markNewTravelPlan() {
    try {
        // 获取最新的旅行计划列表
        const response = await fetch(`${API_BASE}/user/query_travel_plans?userId=${currentUser.userId}`, {
            credentials: 'include'
        });
        const result = await response.json();
        
        if (result.success && result.data && result.data.length > 0) {
            // 获取最新的计划（按创建时间排序的第一个）
            const latestPlan = result.data.sort((a, b) => 
                new Date(b.createTime) - new Date(a.createTime)
            )[0];
            
            if (latestPlan && latestPlan.planId) {
                newTravelPlans.add(latestPlan.planId);
            }
        }
    } catch (error) {
        console.error('标记新旅行计划失败:', error);
    }
}

// 标记新创建的费用预算分析
async function markNewBudgetAnalysis() {
    try {
        // 获取最新的费用预算分析列表
        const response = await fetch(`${API_BASE}/budget/query_budget_analysis?userId=${currentUser.userId}`, {
            credentials: 'include'
        });
        const result = await response.json();
        
        if (result.success && result.data && result.data.length > 0) {
            // 获取最新的分析（按创建时间排序的第一个）
            const latestAnalysis = result.data.sort((a, b) => 
                new Date(b.createTime) - new Date(a.createTime)
            )[0];
            
            if (latestAnalysis && latestAnalysis.analyzeId) {
                newBudgetAnalyses.add(latestAnalysis.analyzeId);
            }
        }
    } catch (error) {
        console.error('标记新费用预算分析失败:', error);
    }
}

// 将音频转换为PCM格式
async function convertToPCM(audioBlob) {
    return new Promise((resolve, reject) => {
        const audioContext = new (window.AudioContext || window.webkitAudioContext)();
        const fileReader = new FileReader();

        fileReader.onload = async (e) => {
            try {
                const arrayBuffer = e.target.result;
                const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
                
                // 转换为16kHz, 16bit, 单声道PCM
                const offlineContext = new OfflineAudioContext(1, audioBuffer.duration * 16000, 16000);
                const source = offlineContext.createBufferSource();
                source.buffer = audioBuffer;
                source.connect(offlineContext.destination);
                source.start();

                const renderedBuffer = await offlineContext.startRendering();
                const pcmData = audioBufferToPCM(renderedBuffer);
                
                resolve(pcmData);
            } catch (error) {
                reject(error);
            }
        };

        fileReader.onerror = reject;
        fileReader.readAsArrayBuffer(audioBlob);
    });
}

// 将AudioBuffer转换为PCM数据
function audioBufferToPCM(audioBuffer) {
    const channelData = audioBuffer.getChannelData(0);
    const pcmData = new Int16Array(channelData.length);
    
    for (let i = 0; i < channelData.length; i++) {
        // 转换为16bit PCM
        const sample = Math.max(-1, Math.min(1, channelData[i]));
        pcmData[i] = sample < 0 ? sample * 0x8000 : sample * 0x7FFF;
    }
    
    return pcmData;
}

// 显示处理中消息
function showProcessingMessage(message) {
    const processingMessage = document.createElement('div');
    processingMessage.id = 'voice-processing-message';
    processingMessage.innerHTML = `
        <div style="position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); 
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
                    color: white; padding: 25px 30px; 
                    border-radius: 15px; z-index: 1000; text-align: center;
                    box-shadow: 0 10px 30px rgba(102, 126, 234, 0.4);
                    min-width: 280px;">
            <div style="font-size: 24px; margin-bottom: 15px; animation: spin 1.5s linear infinite;">⏳</div>
            <div style="font-size: 18px; font-weight: 600; margin-bottom: 8px;">正在处理</div>
            <div style="font-size: 14px; opacity: 0.9;">${message}</div>
        </div>
        <style>
            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
        </style>
    `;
    document.body.appendChild(processingMessage);
}

// 移除处理中消息
function removeProcessingMessage() {
    const processingMessage = document.getElementById('voice-processing-message');
    if (processingMessage) {
        processingMessage.remove();
    }
}

// 显示成功消息
function showSuccessMessage(message) {
    removeProcessingMessage();
    
    const successMessage = document.createElement('div');
    successMessage.id = 'voice-success-message';
    successMessage.innerHTML = `
        <div style="position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); 
                    background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%); 
                    color: white; padding: 25px 30px; 
                    border-radius: 15px; z-index: 1000; text-align: center;
                    box-shadow: 0 10px 30px rgba(76, 175, 80, 0.4);
                    min-width: 280px;">
            <div style="font-size: 24px; margin-bottom: 15px; animation: bounce 0.5s ease-in-out;">✅</div>
            <div style="font-size: 18px; font-weight: 600; margin-bottom: 8px;">处理成功</div>
            <div style="font-size: 14px; opacity: 0.9;">${message}</div>
        </div>
        <style>
            @keyframes bounce {
                0%, 20%, 50%, 80%, 100% { transform: translateY(0); }
                40% { transform: translateY(-10px); }
                60% { transform: translateY(-5px); }
            }
        </style>
    `;
    document.body.appendChild(successMessage);
    
    // 2秒后自动移除
    setTimeout(() => {
        removeSuccessMessage();
    }, 2000);
}

// 移除成功消息
function removeSuccessMessage() {
    const successMessage = document.getElementById('voice-success-message');
    if (successMessage) {
        successMessage.remove();
    }
}

// 显示错误消息
function showErrorMessage(message) {
    removeProcessingMessage();
    
    const errorMessage = document.createElement('div');
    errorMessage.id = 'voice-error-message';
    errorMessage.innerHTML = `
        <div style="position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); 
                    background: linear-gradient(135deg, #f44336 0%, #d32f2f 100%); 
                    color: white; padding: 25px 30px; 
                    border-radius: 15px; z-index: 1000; text-align: center;
                    box-shadow: 0 10px 30px rgba(244, 67, 54, 0.4);
                    min-width: 280px;">
            <div style="font-size: 24px; margin-bottom: 15px; animation: shake 0.5s ease-in-out;">❌</div>
            <div style="font-size: 18px; font-weight: 600; margin-bottom: 8px;">处理失败</div>
            <div style="font-size: 14px; opacity: 0.9;">${message}</div>
        </div>
        <style>
            @keyframes shake {
                0%, 100% { transform: translateX(0); }
                10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
                20%, 40%, 60%, 80% { transform: translateX(5px); }
            }
        </style>
    `;
    document.body.appendChild(errorMessage);
    
    // 2秒后自动移除
    setTimeout(() => {
        removeErrorMessage();
    }, 2000);
}

// 移除错误消息
function removeErrorMessage() {
    const errorMessage = document.getElementById('voice-error-message');
    if (errorMessage) {
        errorMessage.remove();
    }
}

// 高德地图相关函数
let amap = null;
let geolocation = null;
let isAmapInitialized = false;

// 高德地图安全配置
window._AMapSecurityConfig = {
    securityJsCode: "e33a96494b7a911238e11589be02470a",
};

// 初始化高德地图
function initAmap() {
    console.log('开始初始化高德地图...');
    
    // 检查高德地图API是否已加载
    if (typeof AMap === 'undefined') {
        console.log('AMap未定义，开始加载API...');
        // 如果AMap未定义，尝试重新加载API
        loadAmapAPI();
        return;
    }
    
    const mapContainer = document.getElementById('map-container');
    const mapLoading = document.getElementById('map-loading');
    
    // 检查地图容器是否存在
    if (!mapContainer) {
        console.error('地图容器不存在');
        showErrorMessage('地图容器不存在，请刷新页面重试');
        return;
    }
    
    // 如果地图已经初始化，直接显示
    if (isAmapInitialized && amap) {
        console.log('地图已初始化，直接显示');
        mapLoading.style.display = 'none';
        return;
    }
    
    // 确保地图容器是可见的（高德地图初始化需要容器可见）
    const amapSection = document.getElementById('amap');
    if (amapSection && !amapSection.classList.contains('active')) {
        console.log('地图容器不可见，添加active类');
        // 如果地图容器不可见，先显示它
        amapSection.classList.add('active');
    }
    
    // 确保地图容器有正确的尺寸
    if (mapContainer.offsetWidth === 0 || mapContainer.offsetHeight === 0) {
        console.log('地图容器尺寸为0，延迟初始化');
        // 如果容器尺寸为0，延迟初始化
        setTimeout(initAmap, 100);
        return;
    }
    
    console.log('地图容器准备就绪，开始初始化地图');
    // 显示加载状态
    mapLoading.style.display = 'flex';
    
    // 初始化地图
    try {
        amap = new AMap.Map('map', {
            zoom: 13, // 初始缩放级别
            center: [116.397428, 39.90923], // 初始中心点（北京）
            viewMode: '3D', // 使用3D视图
            mapStyle: 'amap://styles/normal' // 地图样式
        });
        
        // 添加地图控件（使用更兼容的方式）
        try {
            // 尝试添加工具栏控件
            if (AMap.ToolBar) {
                amap.addControl(new AMap.ToolBar());
            } else {
                console.warn('ToolBar控件不可用，跳过添加');
            }
            
            // 尝试添加比例尺控件
            if (AMap.Scale) {
                amap.addControl(new AMap.Scale());
            } else {
                console.warn('Scale控件不可用，跳过添加');
            }
            
            // 尝试添加鹰眼控件
            if (AMap.OverView) {
                amap.addControl(new AMap.OverView());
            } else {
                console.warn('OverView控件不可用，跳过添加');
            }
        } catch (controlError) {
            console.warn('添加地图控件时出错:', controlError);
            // 控件添加失败不影响地图基本功能
        }
        
        // 初始化定位插件（使用更兼容的方式）
        try {
            if (AMap.Geolocation) {
                geolocation = new AMap.Geolocation({
                    enableHighAccuracy: true, // 是否使用高精度定位
                    timeout: 10000, // 超时时间
                    buttonPosition: 'RB', // 定位按钮位置
                    showMarker: true, // 定位成功后在定位位置显示点标记
                    showCircle: true, // 定位成功后用圆圈表示定位精度范围
                    panToLocation: true, // 定位成功后自动移动到定位位置
                    zoomToAccuracy: true // 定位成功后调整视野范围到定位精度范围
                });
                
                amap.addControl(geolocation);
            } else {
                console.warn('Geolocation控件不可用，跳过添加');
                // 如果定位控件不可用，使用浏览器原生定位
                geolocation = null;
            }
        } catch (geoError) {
            console.warn('初始化定位插件时出错:', geoError);
            geolocation = null;
            // 定位插件初始化失败不影响地图基本功能
        }
        
        // 绑定定位按钮事件
        document.getElementById('locate-me').addEventListener('click', function() {
            if (geolocation) {
                // 使用高德地图定位
                locateCurrentPosition();
            } else {
                // 使用浏览器原生定位
                useBrowserGeolocation();
            }
        });
        
        // 绑定重置地图按钮事件
        document.getElementById('reset-map').addEventListener('click', function() {
            resetMap();
        });
        
        // 标记为已初始化
        isAmapInitialized = true;
        
        // 隐藏加载状态
        setTimeout(() => {
            mapLoading.style.display = 'none';
        }, 500);
        
    } catch (error) {
        console.error('高德地图初始化失败:', error);
        showErrorMessage('地图初始化失败，请刷新页面重试');
        mapLoading.style.display = 'none';
    }
}

// 加载高德地图API
function loadAmapAPI() {
    console.log('开始加载高德地图API...');
    
    // 检查是否已经在加载中
    if (window.amapLoading) {
        console.log('API正在加载中，跳过重复加载');
        return;
    }
    
    window.amapLoading = true;
    
    // 使用更稳定的API版本和加载方式
    const script = document.createElement('script');
    script.src = 'https://webapi.amap.com/maps?v=1.4.15&key=da444dc7a354e634d66a25b2627f17e9';
    script.onload = function() {
        console.log('高德地图API加载成功');
        window.amapLoading = false;
        
        // 检查API是否完全加载完成
        if (typeof AMap === 'undefined') {
            console.error('AMap对象未定义，API加载可能有问题');
            showErrorMessage('地图API加载异常，请刷新页面重试');
            return;
        }
        
        // API加载成功后重新初始化地图
        setTimeout(initAmap, 100);
    };
    script.onerror = function() {
        console.error('高德地图API加载失败');
        window.amapLoading = false;
        showErrorMessage('高德地图API加载失败，请检查网络连接或API密钥');
        
        // 3秒后重试
        setTimeout(function() {
            console.log('尝试重新加载高德地图API...');
            loadAmapAPI();
        }, 3000);
    };
    
    // 设置超时处理
    setTimeout(function() {
        if (typeof AMap === 'undefined' && window.amapLoading) {
            console.error('高德地图API加载超时');
            window.amapLoading = false;
            showErrorMessage('高德地图API加载超时，请检查网络连接');
        }
    }, 10000);
    
    document.head.appendChild(script);
}

// 定位当前位置
function locateCurrentPosition() {
    // 检查浏览器是否支持定位
    if (!navigator.geolocation) {
        showErrorMessage('您的浏览器不支持定位功能');
        return;
    }
    
    if (!geolocation) {
        showErrorMessage('定位功能未初始化，请先等待地图加载完成');
        return;
    }
    
    updateLocationInfo('定位中...', 'loading');
    
    // 先尝试使用浏览器原生定位获取粗略位置
    navigator.geolocation.getCurrentPosition(
        function(position) {
            console.log('浏览器定位成功:', position);
            // 浏览器定位成功，继续使用高德地图精确定位
            useAmapGeolocation();
        },
        function(error) {
            console.warn('浏览器定位失败:', error);
            // 浏览器定位失败，仍然尝试高德地图定位
            useAmapGeolocation();
        },
        {
            enableHighAccuracy: false, // 先使用低精度定位快速获取位置
            timeout: 5000,
            maximumAge: 300000
        }
    );
}

// 使用浏览器原生定位
function useBrowserGeolocation() {
    // 检查浏览器是否支持定位
    if (!navigator.geolocation) {
        showErrorMessage('您的浏览器不支持定位功能');
        return;
    }
    
    updateLocationInfo('定位中...', 'loading');
    
    navigator.geolocation.getCurrentPosition(
        function(position) {
            console.log('浏览器定位成功:', position);
            
            // 获取经纬度
            const lat = position.coords.latitude;
            const lng = position.coords.longitude;
            
            // 更新位置信息
            const locationText = `经度: ${lng.toFixed(6)}, 纬度: ${lat.toFixed(6)}`;
            updateLocationInfo(locationText, 'success');
            
            // 在地图上显示定位点（如果地图已初始化）
            if (amap) {
                // 清除之前的标记
                amap.clearMap();
                
                // 添加定位标记
                const marker = new AMap.Marker({
                    position: [lng, lat],
                    title: '我的位置',
                    content: '<div style="background: #667eea; color: white; padding: 5px 10px; border-radius: 15px; font-size: 12px;">我的位置</div>'
                });
                
                amap.add(marker);
                
                // 移动到定位位置
                amap.setCenter([lng, lat]);
                amap.setZoom(15);
            }
            
            showSuccessMessage('定位成功');
        },
        function(error) {
            console.error('浏览器定位失败:', error);
            let errorMessage = '定位失败';
            
            // 根据错误类型提供更详细的错误信息
            switch (error.code) {
                case error.PERMISSION_DENIED:
                    errorMessage = '定位权限被拒绝，请在浏览器设置中允许定位权限';
                    break;
                case error.POSITION_UNAVAILABLE:
                    errorMessage = '无法获取位置信息，请检查网络连接';
                    break;
                case error.TIMEOUT:
                    errorMessage = '定位超时，请重试';
                    break;
                default:
                    errorMessage = '定位失败，请重试';
            }
            
            updateLocationInfo('定位失败', 'error');
            showErrorMessage(errorMessage);
        },
        {
            enableHighAccuracy: true,
            timeout: 10000,
            maximumAge: 300000
        }
    );
}

// 使用高德地图进行精确定位
function useAmapGeolocation() {
    geolocation.getCurrentPosition(function(status, result) {
        if (status === 'complete') {
            // 定位成功
            const position = result.position;
            const address = result.formattedAddress;
            
            // 更新位置信息
            const locationText = address || `经度: ${position.lng.toFixed(6)}, 纬度: ${position.lat.toFixed(6)}`;
            updateLocationInfo(locationText, 'success');
            
            // 在地图上显示定位点
            if (amap) {
                // 清除之前的标记
                amap.clearMap();
                
                // 添加定位标记
                const marker = new AMap.Marker({
                    position: position,
                    title: '我的位置',
                    content: '<div style="background: #667eea; color: white; padding: 5px 10px; border-radius: 15px; font-size: 12px;">我的位置</div>'
                });
                
                amap.add(marker);
                
                // 移动到定位位置
                amap.setCenter(position);
                amap.setZoom(15);
            }
            
            showSuccessMessage('定位成功');
        } else {
            // 定位失败
            console.error('高德地图定位失败:', result);
            let errorMessage = '定位失败';
            
            // 根据错误类型提供更详细的错误信息
            if (result && result.info) {
                switch (result.info) {
                    case 'PERMISSION_DENIED':
                        errorMessage = '定位权限被拒绝，请在浏览器设置中允许定位权限';
                        break;
                    case 'POSITION_UNAVAILABLE':
                        errorMessage = '无法获取位置信息，请检查网络连接';
                        break;
                    case 'TIMEOUT':
                        errorMessage = '定位超时，请重试';
                        break;
                    default:
                        errorMessage = result.info;
                }
            }
            
            updateLocationInfo('定位失败', 'error');
            showErrorMessage(errorMessage);
        }
    });
}

// 重置地图
function resetMap() {
    if (!amap) return;
    
    // 清除地图上的标记
    amap.clearMap();
    
    // 重置地图中心和缩放级别
    amap.setCenter([116.397428, 39.90923]);
    amap.setZoom(13);
    
    // 重置位置信息
    updateLocationInfo('未获取位置信息', 'default');
    
    showSuccessMessage('地图已重置');
}

// 更新位置信息显示
function updateLocationInfo(text, status = 'default') {
    const locationInfo = document.getElementById('current-location');
    if (!locationInfo) return;
    
    // 清除之前的样式类
    locationInfo.className = '';
    
    // 根据状态添加样式
    switch (status) {
        case 'loading':
            locationInfo.classList.add('location-loading');
            break;
        case 'success':
            locationInfo.classList.add('location-success');
            break;
        case 'error':
            locationInfo.classList.add('location-error');
            break;
        default:
            locationInfo.classList.add('location-default');
    }
    
    locationInfo.textContent = text;
}

// 页面加载时初始化位置信息显示
function initializeLocationInfo() {
    updateLocationInfo('未获取位置信息', 'default');
}

// 万能助手相关函数
let universalAssistantHistory = [];

// 初始化万能助手
function initUniversalAssistant() {
    // 加载历史对话记录
    loadUniversalAssistantHistory();
    
    // 绑定发送按钮事件
    const sendButton = document.getElementById('send-question');
    const inputField = document.getElementById('question-input');
    const clearResponseButton = document.getElementById('clear-response');
    const clearHistoryButton = document.getElementById('clear-history');
    
    if (sendButton) {
        sendButton.addEventListener('click', function() {
            handleUniversalAssistantSubmit();
        });
    }
    
    if (inputField) {
        // 绑定回车键发送
        inputField.addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                handleUniversalAssistantSubmit();
            }
        });
    }
    
    if (clearResponseButton) {
        clearResponseButton.addEventListener('click', function() {
            clearUniversalAssistantResponse();
        });
    }
    
    if (clearHistoryButton) {
        clearHistoryButton.addEventListener('click', function() {
            clearUniversalAssistantHistory();
        });
    }
    
    // 显示历史对话
    displayUniversalAssistantHistory();
}

// 处理万能助手提交
function handleUniversalAssistantSubmit() {
    const inputField = document.getElementById('question-input');
    const question = inputField.value.trim();
    
    if (!question) {
        showErrorMessage('请输入问题');
        return;
    }
    
    if (!currentUser || !currentUser.userId) {
        showErrorMessage('请先登录');
        return;
    }
    
    // 显示加载状态
    showUniversalAssistantLoading(question);
    
    // 清空输入框
    inputField.value = '';
    
    // 调用API
    callUniversalAssistantAPI(question);
}

// 显示万能助手加载状态
function showUniversalAssistantLoading(question) {
    const resultContainer = document.getElementById('response-content');
    const loadingContainer = document.getElementById('assistant-loading');
    const responseContainer = document.getElementById('assistant-response');
    
    // 显示加载容器，隐藏响应容器
    loadingContainer.classList.remove('hidden');
    responseContainer.classList.add('hidden');
    
    // 清空结果容器
    resultContainer.innerHTML = '';
    
    // 创建加载中的消息
    const loadingMessage = document.createElement('div');
    loadingMessage.className = 'assistant-message assistant-loading';
    loadingMessage.innerHTML = `
        <div class="message-content">
            <div class="message-question">
                <strong>您的问题：</strong>${question}
            </div>
            <div class="message-answer">
                <div class="loading-indicator">
                    <div class="loading-spinner"></div>
                    <span>正在分析您的问题，请稍候...</span>
                </div>
            </div>
        </div>
        <div class="message-time">${new Date().toLocaleString()}</div>
    `;
    
    // 添加到结果区域
    resultContainer.appendChild(loadingMessage);
    
    // 滚动到底部
    resultContainer.scrollTop = resultContainer.scrollHeight;
}

// 调用万能助手API
async function callUniversalAssistantAPI(question) {
    try {
        const response = await fetch(`${API_BASE}/v1/any_question`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                userId: currentUser.userId,
                question: question
            })
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.json();
        
        // 处理API响应
        handleUniversalAssistantResponse(question, data);
        
    } catch (error) {
        console.error('万能助手API调用失败:', error);
        showUniversalAssistantError(question, '网络请求失败，请检查网络连接后重试');
    }
}

// 处理万能助手响应
function handleUniversalAssistantResponse(question, responseData) {
    const resultContainer = document.getElementById('response-content');
    const loadingContainer = document.getElementById('assistant-loading');
    const responseContainer = document.getElementById('assistant-response');
    
    // 隐藏加载容器，显示响应容器
    loadingContainer.classList.add('hidden');
    responseContainer.classList.remove('hidden');
    
    // 清空结果容器
    resultContainer.innerHTML = '';
    
    // 创建成功消息
    const successMessage = document.createElement('div');
    successMessage.className = 'assistant-message assistant-success';
    
    // 格式化响应内容
    const formattedAnswer = formatAssistantAnswer(responseData.data || responseData.answer || responseData.message || '暂时无法回答您的问题');
    
    successMessage.innerHTML = `
        <div class="message-content">
            <div class="message-question">
                <strong>您的问题：</strong>${question}
            </div>
            <div class="message-answer">
                <strong>助手回答：</strong>
                <div class="answer-content">${formattedAnswer}</div>
            </div>
        </div>
        <div class="message-time">${new Date().toLocaleString()}</div>
    `;
    
    resultContainer.appendChild(successMessage);
    
    // 滚动到底部
    resultContainer.scrollTop = resultContainer.scrollHeight;
    
    // 保存到历史记录
    saveUniversalAssistantHistory(question, formattedAnswer);
}

// 显示万能助手错误
function showUniversalAssistantError(question, errorMessage) {
    const resultContainer = document.getElementById('response-content');
    const loadingContainer = document.getElementById('assistant-loading');
    const responseContainer = document.getElementById('assistant-response');
    
    // 隐藏加载容器，显示响应容器
    loadingContainer.classList.add('hidden');
    responseContainer.classList.remove('hidden');
    
    // 清空结果容器
    resultContainer.innerHTML = '';
    
    // 创建错误消息
    const errorMessageDiv = document.createElement('div');
    errorMessageDiv.className = 'assistant-message assistant-error';
    errorMessageDiv.innerHTML = `
        <div class="message-content">
            <div class="message-question">
                <strong>您的问题：</strong>${question}
            </div>
            <div class="message-answer">
                <strong>抱歉：</strong>
                <div class="error-content">${errorMessage}</div>
            </div>
        </div>
        <div class="message-time">${new Date().toLocaleString()}</div>
    `;
    
    resultContainer.appendChild(errorMessageDiv);
    
    // 滚动到底部
    resultContainer.scrollTop = resultContainer.scrollHeight;
    
    // 保存到历史记录
    saveUniversalAssistantHistory(question, `错误：${errorMessage}`);
}

// 格式化助手回答
function formatAssistantAnswer(answer) {
    // 简单的文本格式化
    return answer
        .replace(/\\n/g, '<br>')
        .replace(/\\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;')
        .replace(/  /g, '&nbsp;&nbsp;');
}

// 保存对话历史到本地存储
function saveUniversalAssistantHistory(question, answer) {
    const conversation = {
        id: Date.now(),
        question: question,
        answer: answer,
        timestamp: new Date().toISOString(),
        displayTime: new Date().toLocaleString()
    };
    
    universalAssistantHistory.unshift(conversation);
    
    // 限制历史记录数量（最多50条）
    if (universalAssistantHistory.length > 50) {
        universalAssistantHistory = universalAssistantHistory.slice(0, 50);
    }
    
    // 保存到localStorage
    localStorage.setItem('universalAssistantHistory', JSON.stringify(universalAssistantHistory));
    
    // 更新历史记录显示
    displayUniversalAssistantHistory();
}

// 加载对话历史
function loadUniversalAssistantHistory() {
    try {
        const savedHistory = localStorage.getItem('universalAssistantHistory');
        if (savedHistory) {
            universalAssistantHistory = JSON.parse(savedHistory);
        }
    } catch (error) {
        console.error('加载万能助手历史记录失败:', error);
        universalAssistantHistory = [];
    }
}

// 显示对话历史
function displayUniversalAssistantHistory() {
    const historyContainer = document.getElementById('history-list');
    const historySection = document.getElementById('assistant-history');
    
    if (!historyContainer) return;
    
    // 清空历史容器
    historyContainer.innerHTML = '';
    
    if (universalAssistantHistory.length === 0) {
        historyContainer.innerHTML = '<div class="no-history">暂无历史对话记录</div>';
        // 隐藏历史记录区域
        historySection.classList.add('hidden');
        return;
    }
    
    // 显示历史记录（最多显示10条）
    const displayHistory = universalAssistantHistory.slice(0, 10);
    
    // 显示历史记录区域
    historySection.classList.remove('hidden');
    
    displayHistory.forEach(conversation => {
        const historyItem = document.createElement('div');
        historyItem.className = 'history-item';
        historyItem.innerHTML = `
            <div class="history-question">
                <strong>Q:</strong> ${conversation.question}
            </div>
            <div class="history-answer">
                <strong>A:</strong> ${conversation.answer.substring(0, 100)}${conversation.answer.length > 100 ? '...' : ''}
            </div>
            <div class="history-time">${conversation.displayTime}</div>
            <div class="history-actions">
                <button class="btn-history" onclick="loadHistoryToInput('${conversation.id}')">
                    <span class="btn-icon">↻</span>
                    重新提问
                </button>
                <button class="btn-history" onclick="deleteHistoryItem('${conversation.id}')">
                    <span class="btn-icon">🗑️</span>
                    删除
                </button>
            </div>
        `;
        
        historyContainer.appendChild(historyItem);
    });
}

// 加载历史记录到输入框
function loadHistoryToInput(historyId) {
    const conversation = universalAssistantHistory.find(item => item.id.toString() === historyId);
    if (conversation) {
        const inputField = document.getElementById('question-input');
        inputField.value = conversation.question;
        inputField.focus();
    }
}

// 删除历史记录项
function deleteHistoryItem(historyId) {
    universalAssistantHistory = universalAssistantHistory.filter(item => item.id.toString() !== historyId);
    
    // 更新本地存储
    localStorage.setItem('universalAssistantHistory', JSON.stringify(universalAssistantHistory));
    
    // 更新显示
    displayUniversalAssistantHistory();
}

// 清空所有历史记录
function clearUniversalAssistantHistory() {
    if (confirm('确定要清空所有历史对话记录吗？')) {
        universalAssistantHistory = [];
        localStorage.removeItem('universalAssistantHistory');
        displayUniversalAssistantHistory();
        showSuccessMessage('历史记录已清空');
    }
}

// 清空助手响应
function clearUniversalAssistantResponse() {
    const resultContainer = document.getElementById('response-content');
    const responseContainer = document.getElementById('assistant-response');
    
    if (resultContainer) {
        resultContainer.innerHTML = '';
    }
    
    if (responseContainer) {
        responseContainer.classList.add('hidden');
    }
    
    showSuccessMessage('响应已清除');
}

// ==================== 路线规划功能 ====================

// 路线规划相关变量
let driving = null; // 驾车路线规划插件实例
let currentRoute = null; // 当前路线

// 初始化路线规划功能
function initRoutePlanning() {
    console.log('初始化路线规划功能');
    
    // 绑定路线规划按钮事件
    document.getElementById('route-planning-btn').addEventListener('click', function() {
        toggleRoutePlanningPanel();
    });
    
    // 绑定关闭路线规划面板事件
    document.getElementById('close-route-panel').addEventListener('click', function() {
        closeRoutePlanningPanel();
    });
    
    // 绑定搜索路线按钮事件
    document.getElementById('search-route').addEventListener('click', function() {
        searchRoute();
    });
    
    // 绑定清除路线按钮事件
    document.getElementById('clear-route').addEventListener('click', function() {
        clearRoute();
    });
    
    // 绑定输入框回车事件
    document.getElementById('start-point').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            searchRoute();
        }
    });
    
    document.getElementById('end-point').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            searchRoute();
        }
    });
}

// 切换路线规划面板显示/隐藏
function toggleRoutePlanningPanel() {
    const panel = document.getElementById('route-planning-panel');
    if (panel.classList.contains('hidden')) {
        openRoutePlanningPanel();
    } else {
        closeRoutePlanningPanel();
    }
}

// 打开路线规划面板
function openRoutePlanningPanel() {
    const panel = document.getElementById('route-planning-panel');
    panel.classList.remove('hidden');
    
    // 清空之前的路线结果
    clearRouteResults();
    
    console.log('路线规划面板已打开');
}

// 关闭路线规划面板
function closeRoutePlanningPanel() {
    const panel = document.getElementById('route-planning-panel');
    panel.classList.add('hidden');
    
    console.log('路线规划面板已关闭');
}

// 使用当前位置作为起点
function useCurrentLocationForRoute() {
    const startPointInput = document.getElementById('start-point');
    
    // 检查地图是否已初始化
    if (!amap || !isAmapInitialized) {
        showErrorMessage('请先等待地图加载完成');
        return;
    }
    
    // 检查是否有当前位置信息
    const currentLocation = document.getElementById('current-location').textContent;
    if (currentLocation === '未获取位置信息') {
        showErrorMessage('请先定位当前位置');
        return;
    }
    
    // 使用当前位置作为起点
    startPointInput.value = currentLocation;
    showSuccessMessage('已使用当前位置作为起点');
}

// 搜索路线
function searchRoute() {
    console.log('开始搜索路线...');
    
    // 获取输入值
    const startPoint = document.getElementById('start-point').value.trim();
    const endPoint = document.getElementById('end-point').value.trim();
    
    // 验证输入
    if (!startPoint) {
        showErrorMessage('请输入起点地址');
        return;
    }
    
    if (!endPoint) {
        showErrorMessage('请输入终点地址');
        return;
    }
    
    // 检查地图是否已初始化
    if (!amap || !isAmapInitialized) {
        showErrorMessage('请先等待地图加载完成');
        return;
    }
    
    // 显示加载状态
    showRouteLoading();
    
    // 清除之前的路线
    clearRoute();
    
    // 加载驾车路线规划插件
    loadDrivingPlugin(startPoint, endPoint);
}

// 加载驾车路线规划插件
function loadDrivingPlugin(startPoint, endPoint) {
    console.log('加载驾车路线规划插件...');
    
    // 检查AMap对象是否可用
    if (typeof AMap === 'undefined') {
        showRouteError('地图API未加载完成，请稍后重试');
        return;
    }
    
    // 使用AMap.plugin加载驾车插件
    AMap.plugin(['AMap.Driving'], function() {
        console.log('AMap.Driving插件加载成功');
        
        try {
            // 创建驾车路线规划实例
            driving = new AMap.Driving({
                map: amap,
                panel: 'route-panel',
                policy: AMap.DrivingPolicy.LEAST_TIME, // 默认使用最快路线
                hideMarkers: false, // 显示标记点
                showTraffic: true // 显示实时路况
            });
            
            // 定义路线点
            const points = [
                { keyword: startPoint },
                { keyword: endPoint }
            ];
            
            // 搜索路线
            driving.search(points, function(status, result) {
                handleRouteSearchResult(status, result, startPoint, endPoint);
            });
            
        } catch (error) {
            console.error('创建驾车路线规划实例失败:', error);
            showRouteError('路线规划功能初始化失败：' + error.message);
        }
    });
}

// 处理路线搜索结果
function handleRouteSearchResult(status, result, startPoint, endPoint) {
    console.log('路线搜索结果状态:', status);
    
    // 隐藏加载状态
    hideRouteLoading();
    
    if (status === 'complete') {
        // 查询成功
        currentRoute = result;
        displayRouteResults(result, startPoint, endPoint);
        showSuccessMessage('路线规划成功');
    } else if (status === 'no_data') {
        // 查询无结果
        showRouteError('未找到从 "' + startPoint + '" 到 "' + endPoint + '" 的可行路线');
    } else {
        // 查询错误
        const errorMsg = result && result.info ? result.info : '路线规划失败';
        showRouteError('路线规划失败：' + errorMsg);
    }
}

// 显示路线规划结果
function displayRouteResults(result, startPoint, endPoint) {
    const resultsContainer = document.getElementById('route-results');
    const panelContent = document.getElementById('route-panel');
    
    if (!resultsContainer || !panelContent) return;
    
    // 清空之前的结果
    panelContent.innerHTML = '';
    
    // 检查是否有路线数据
    if (!result.routes || result.routes.length === 0) {
        panelContent.innerHTML = '<div class="route-info route-error">未找到可行路线</div>';
        return;
    }
    
    // 显示路线信息
    const route = result.routes[0]; // 取第一条路线
    
    // 创建路线信息卡片
    const routeInfo = document.createElement('div');
    routeInfo.className = 'route-info';
    
    // 计算总距离和总时间
    const totalDistance = (route.distance / 1000).toFixed(1); // 转换为公里
    const totalTime = Math.round(route.time / 60); // 转换为分钟
    
    routeInfo.innerHTML = `
        <h4>路线规划结果</h4>
        <p><strong>起点：</strong>${startPoint || '当前位置'}</p>
        <p><strong>终点：</strong>${endPoint}</p>
        <p><strong>总距离：</strong>${totalDistance} 公里</p>
        <p><strong>预计时间：</strong>${totalTime} 分钟</p>
        <p><strong>路线策略：</strong>最快路线</p>
    `;
    
    panelContent.appendChild(routeInfo);
    
    console.log('路线规划结果显示完成');
}

// 清除路线
function clearRoute() {
    if (driving && currentRoute) {
        // 清除地图上的路线
        driving.clear();
        currentRoute = null;
    }
    
    // 清空路线结果
    clearRouteResults();
    
    console.log('路线已清除');
    showSuccessMessage('路线已清除');
}

// 清空路线结果
function clearRouteResults() {
    const panelContent = document.getElementById('route-panel');
    if (panelContent) {
        panelContent.innerHTML = '';
    }
}

// 显示路线加载状态
function showRouteLoading() {
    const panelContent = document.getElementById('route-panel');
    if (panelContent) {
        panelContent.innerHTML = `
            <div class="route-loading">
                <div class="loading-spinner"></div>
                <p>正在规划路线，请稍候...</p>
            </div>
        `;
    }
}

// 隐藏路线加载状态
function hideRouteLoading() {
    // 加载状态会在显示结果时自动被替换
}

// 显示路线错误信息
function showRouteError(message) {
    const panelContent = document.getElementById('route-panel');
    if (panelContent) {
        panelContent.innerHTML = `
            <div class="route-info route-error">
                <h4>路线规划失败</h4>
                <p>${message}</p>
            </div>
        `;
    }
    
    console.error('路线规划错误:', message);
}

// 在页面加载完成后初始化路线规划功能
document.addEventListener('DOMContentLoaded', function() {
    // 延迟初始化路线规划功能，确保其他功能先加载
    setTimeout(initRoutePlanning, 1000);
});